﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace BalanceControl
{
    /// <summary>
    /// PageSerial.xaml 的交互逻辑
    /// </summary>
    public partial class PageSerial : Page
    {
        private bool isASCII = true;
        private StringBuilder receiveBuffer = new StringBuilder();

        private SerialPort serialPort = new SerialPort();
        DispatcherTimer timer = new DispatcherTimer();

        public PageSerial()
        {
            InitializeComponent();
            serialPort.DataReceived += SerialPort_DataReceived;
            timer.Interval = new TimeSpan(0, 0, 0, 0,100);
            timer.Tick += Timer_Tick;
            timer.Start();
        }

        private void Timer_Tick(object sender, EventArgs e)
        {
            txtReceive.Text = receiveBuffer.ToString();
        }

        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            int readlen = serialPort.BytesToRead;
            if (readlen > 0)
            {
                byte[] tempBuffer = new byte[readlen];
                int count = serialPort.Read(tempBuffer, 0, readlen);
                if (count > 0)
                {

                    Dispatcher.Invoke(() =>
                    {
                        Data_Display(tempBuffer);
                    });
                }
            }
        }

        private void Data_Display(byte[] data)
        {
            if (isASCII == true)
            {
                receiveBuffer.Append(Encoding.Default.GetString(data));
            }
            else
            {
                foreach (byte b in data)
                {
                    receiveBuffer.Append(b.ToString("X2") + " ");
                }
            }
        }

        private void ComboBox_DropDownOpened(object sender, EventArgs e)
        {
            cbSerialPort.Items.Clear();
            foreach (string name in SerialPort.GetPortNames())
            {
                cbSerialPort.Items.Add(name);
            }
        }

        private void btnSerialOpen_Click(object sender, RoutedEventArgs e)
        {
            //串口已打开
            if (serialPort.IsOpen)
            {
                serialPort.Close();
                btnSerialOpen.Content = "打开";
                return;
            }

            if (cbSerialPort.SelectedItem == null || cbSerialPort.SelectedItem.ToString() == "")
            {
                MessageBox.Show("请选择正确的端口号！");
                return;
            }
            int band = 0;
            if (cbSerialBaud.SelectedItem == null || cbSerialBaud.SelectedItem.ToString() == "")
            {
                MessageBox.Show("请选择正确的波特率！");
                return;
            }
            try
            {
                serialPort.PortName = cbSerialPort.Text;
                serialPort.BaudRate = int.Parse(cbSerialBaud.Text);
                serialPort.Open();
                if (serialPort.IsOpen)
                {
                    //打开串口成功
                    btnSerialOpen.Content = "关闭";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("打开串口失败");
                Console.WriteLine(ex.StackTrace);
            }
        }
    }
}
